<template>
  <h1>购物车列表</h1>
  <div>

<!--     新增全选、全反选操作区-->
    <div style="margin-bottom: 10px;">
      <el-button type="primary" v-model="selectAll"  @click="handleSelectAll">全选</el-button>
      <el-button type="primary" @click="handleInverseSelect">反选</el-button>
    </div>

    <div>
      <el-table :data="tableData" style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="price" label="商品图片" width="180">
          <template #default="scope">
            <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.goods.image"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                show-progress
                :initial-index="4"
                fit="cover"
                fallback-src="https://via.placeholder.com/100"
            />
          </template>
        </el-table-column>
        <el-table-column prop="goods.name" label="商品名称" width="180" />
        <el-table-column prop="goods.sale" label="商品售价" width="180" />
        <el-table-column prop="goods.price" label="商品原价" width="180"/>
        <el-table-column prop="score" label="积分" width="180"/>
        <el-table-column prop="quantity" label="数量" width="180">
<!--          <template #default="scope">-->
<!--            <el-input-number v-model="num" :min="1" :max="10" @change="handleChange" />-->
<!--          </template>-->
        </el-table-column>
        <el-table-column prop="weight" label="重量" width="180"/>
        <el-table-column prop="goods.sale" label="商品合计" width="180"/>


        <el-table-column label="操作" width="180" >
          <template #default="scope">
            <el-button type="warning" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>



  </div>

</template>

<script lang="ts" setup>
import { ref , onMounted ,reactive,watch } from 'vue'
import axios from "axios";
import { useRouter } from 'vue-router'
import {ElTable, ElImage, ElButton, ElCheckbox, ElMessage} from 'element-plus' // 引入 ElTable 类型（若用 TS 可增强类型提示）


const tableData = ref([])
const router = useRouter()
const selectedRows = ref([]) // 前端临时选中
const selectAll = ref(false) // 全选状态


function getData(){
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token){
    alert('请先登录')
    router.push('/login')
  }
  if (token){
    axios.get('http://localhost:8000/api/cartDetail/',{headers:{'Authorization':`Bearer ${token}`}}).then(res=>{
      console.log(res)
      if (res.data.code === 1){
        tableData.value = res.data.data
      }
    }).catch(err=>{
      console.log(err)
      alert('获取购物车列表失败'||err)
    })
  }
}


function handleDelete(row) {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    alert('请先登录')
    router.push('/login')
  }
  if (token) {
    console.log(row)
    axios.post(`http://localhost:8000/api/cartDelete/`,{goods_id:row.goods.id },{headers: {'Authorization': `Bearer ${token}`}}).then(res => {
      console.log(res)
      if (res.data.code === 1) {
        alert('删除成功')
        getData()
      } else {
        alert('删除失败' || res.data.message)
      }
    }).catch(err => {
      alert('删除失败' || err)
    })
  }
}








// 全选函数（原逻辑补充：若全选，勾选所有；否则取消所有）
function handleSelectAll(){
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token){
    alert('请先登录')
    router.push('/login')
    return
  }

  axios.post(`http://localhost:8000/api/cartAllUpdate/`,{is_selected:selectAll.value ? 0 : 1}).then(res=>{
    if (res.data.code === 1){
      alert('操作成功')
    }else {
      alert('操作失败' || res.data.message)
    }
  })
}







// 反选函数
function handleInverseSelect() {
  let token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    alert('请先登录')
    router.push('/login')
    return
  }
  // 1. 调接口反选（假设后端有接口支持）
  axios.post(
      'http://localhost:8000/api/cartInverseSelect/',
      // {goods_id:},
      { headers: { 'Authorization': `Bearer ${token}` } }
  ).then(res => {
    if (res.data.code === 1) {
      getData() // 重新拉取数据，前端自动更新
    }
  })
}





// 监听表格多选变化：更新全选状态
const onSelectionChange = (val) => {
  selectedRows.value = val
}


onMounted(
    ()=>{
      getData()
    })
</script>

<style scoped>
.el-image {
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>